package com.zhy.baselibrary.utils

import android.R
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.os.Build
import android.provider.Settings
import android.util.DisplayMetrics
import android.view.*
import androidx.annotation.RequiresApi
import androidx.core.view.ViewCompat
import java.lang.ref.WeakReference

/**
 * 设置工具
 */
object StatusBarUtils {
    /**
     * 设置状态栏透明
     *
     * @param activity
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun translucentStatusBar(activity: WeakReference<Activity>) {
        val window = activity.get()!!.window
        //添加Flag把状态栏设为可绘制模式
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        //如果为全透明模式，取消设置Window半透明的Flag
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        //设置状态栏为透明
        window.statusBarColor = Color.TRANSPARENT
        //设置window的状态栏不可见
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        } else {
            window.decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        }
        //view不根据系统窗口来调整自己的布局
        val mContentView =
                window.findViewById<View>(Window.ID_ANDROID_CONTENT) as ViewGroup
        val mChildView = mContentView.getChildAt(0)
        if (mChildView != null) {
            mChildView.fitsSystemWindows = false
            ViewCompat.requestApplyInsets(mChildView)
        }
    }

    /**
     * 获取虚拟按键高度
     *
     * @param context
     * @return
     */
    fun getStatusBarHeight(context: WeakReference<Context>): Int {
        val resources = context.get()!!.resources
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        return resources.getDimensionPixelSize(resourceId)
    }
    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    fun statusBarHeight(mContext: Context): Int {
        var result = 0
        var resourceId = mContext.resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = mContext.resources.getDimensionPixelSize(resourceId)
        }
        return (result / mContext.resources.displayMetrics.density).toInt()
    }
    /**
     * 改变魅族的状态栏字体为黑色，要求FlyMe4以上
     */
    private fun processFlyMe(isLightStatusBar: Boolean, activity: Activity) {
        val lp = activity.window.attributes
        try {
            val instance =
                    Class.forName("android.view.WindowManager\$LayoutParams")
            val value = instance.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON").getInt(lp)
            val field = instance.getDeclaredField("meizuFlags")
            field.isAccessible = true
            val origin = field.getInt(lp)
            if (isLightStatusBar) {
                field[lp] = origin or value
            } else {
                field[lp] = value.inv() and origin
            }
        } catch (ignored: Exception) {
            ignored.printStackTrace()
        }
    }

    /**
     * 改变小米的状态栏字体颜色为黑色, 要求MIUI6以上  lightStatusBar为真时表示黑色字体
     */
    fun processMIUI(lightStatusBar: Boolean, activity: Activity) {
//        val clazz: Class<Window> = activity.window.javaClass
//        try {
//            val darkModeFlag: Int
//            val layoutParams =
//                Class.forName("android.view.MiuiWindowManager\$LayoutParams")
//            val field =
//                layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE")
//            darkModeFlag = field.getInt(layoutParams)
//            val extraFlagField = clazz.getMethod(
//                "setExtraFlags",
//                Int::class.javaPrimitiveType,
//                Int::class.javaPrimitiveType
//            )
//            extraFlagField.invoke(
//                activity.window,
//                if (lightStatusBar) darkModeFlag else 0,
//                darkModeFlag
//            )
//        } catch (ignored: Exception) {
//            ignored.printStackTrace()
//        }
    }

    /**
     * 设置状态栏文字色值为深色调
     * @param useDart 是否使用深色调
     * @param activity
     */
    fun setStatusTextColor(useDart: Boolean, activity: Activity) {
        when (Build.BRAND) {
            "Xiaomi" -> {
                processMIUI(useDart, activity)
            }
            "Meizu" -> {
                processFlyMe(useDart, activity)
            }
            else -> {
                if (useDart) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        activity.window.decorView.systemUiVisibility =
                                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                    }
                } else {
                    activity.window.decorView.systemUiVisibility =
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                }
                activity.window.decorView
                        .findViewById<View>(R.id.content).setPadding(0, 0, 0, 0)
            }
        }
    }

    //获取底部虚拟键盘的高度
    fun screenHeight(mContext: Context?): Float {
        if (mContext == null) {
            return 0F
        }
        var vh = 0F
        val wm = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val display = wm.defaultDisplay
        val dm = DisplayMetrics()
        try {
            @SuppressWarnings("rawtypes")
            val c = Class.forName("android.view.Display")
            @SuppressWarnings("unchecked")
            val method = c.getMethod("getRealMetrics", DisplayMetrics::class.java)
            method.invoke(display, dm)
            vh = (dm.heightPixels - display.height).toFloat()

        } catch (e: Exception) {
        }
        if (isMIUI()) {
            if (isFullScreen(mContext)) {
                vh = 0F
            }
        } else {
            if (!hasDeviceNavigationBar(mContext)) {
                vh = 0F
            }
        }
        val barVh = getStatusBarHeight(WeakReference(mContext))
        if (vh>barVh){
            return (vh - barVh) / mContext.resources.displayMetrics.density
        }else{
            return 0F
        }
    }

    private fun isFullScreen(context: Context): Boolean {
        // true 是手势，默认是 false
        return Settings.Global.getInt(context.contentResolver, "force_fsg_nav_bar", 0) !== 0
    }

    private fun isMIUI(): Boolean {
        val manufacturer = Build.MANUFACTURER
        // 这个字符串可以自己定义,例如判断华为就填写huawei,魅族就填写meizu
        return "xiaomi" == manufacturer
    }

    /**
     * 获取是否有虚拟按键
     * 通过判断是否有物理返回键反向判断是否有虚拟按键
     *
     * @param context
     * @return
     */
    private fun hasDeviceNavigationBar(context: Context): Boolean {

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            val display = (context as Activity).getWindowManager().getDefaultDisplay()
            val size = Point()
            val realSize = Point()
            display.getSize(size)
            display.getRealSize(realSize)
            realSize.y != size.y
        } else {
            val menu = ViewConfiguration.get((context as Activity)).hasPermanentMenuKey()
            val back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
            !(menu || back)
        }
    }
}